package com.xfcy.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xfcy.blog.common.R;
import com.xfcy.blog.common.constant.Constant;
import com.xfcy.blog.common.constant.RedisConstant;
import com.xfcy.blog.common.constant.SqlConstant;
import com.xfcy.blog.common.enums.UploadEnum;
import com.xfcy.blog.common.enums.YesOrNoEnum;
import com.xfcy.blog.dto.PhotoAlbumDTO;
import com.xfcy.blog.entity.Photo;
import com.xfcy.blog.mapper.PhotoAlbumMapper;
import com.xfcy.blog.entity.PhotoAlbum;
import com.xfcy.blog.mapper.PhotoMapper;
import com.xfcy.blog.service.PhotoAlbumService;
import com.xfcy.blog.service.SystemConfigService;
import com.xfcy.blog.strategy.FileUploadStrategy;
import com.xfcy.blog.strategy.context.FileUploadStrategyContext;
import com.xfcy.blog.utils.BeanCopyUtil;
import com.xfcy.blog.vo.PhotoAlbumsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 相册(PhotoAlbum)表服务实现类
 *
 * @author 晓风残月Lx
 * @since 2023-04-09 11:03:06
 */
@Service("photoAlbumService")
public class PhotoAlbumServiceImpl extends ServiceImpl<PhotoAlbumMapper, PhotoAlbum> implements PhotoAlbumService {

    @Resource
    private FileUploadStrategyContext fileUploadStrategyContext;

    @Autowired
    private PhotoAlbumMapper photoAlbumMapper;

    @Autowired
    private PhotoMapper photoMapper;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 后台相册列表查询
     * @param pageNo
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public R listAlbum(Integer pageNo, Integer pageSize, String name) {
        Page<PhotoAlbumsVO> photoAlbumsVOPage = baseMapper.listAlbum(new Page<>(pageNo, pageSize), name);
        return R.success(photoAlbumsVOPage);
    }

    /**
     * 相册详情
     * @param id
     * @return
     */
    @Override
    public R getAlbumById(Integer id) {
        PhotoAlbumsVO photoAlbumsVO = baseMapper.getAlbumById(id);
        Integer photoCount = photoMapper.selectCount(new QueryWrapper<Photo>().eq(SqlConstant.ALBUM_ID, photoAlbumsVO.getId()));
        photoAlbumsVO.setPhotoCount(photoCount);
        return R.success(photoAlbumsVO);
    }

    /**
     * 添加相册
     * @param photoAlbumDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addPhotoAlbum(PhotoAlbumDTO photoAlbumDTO) {
        PhotoAlbum photoAlbum = BeanCopyUtil.copyObject(photoAlbumDTO, PhotoAlbum.class);
        int insert = baseMapper.insert(photoAlbum);

        if (insert > Constant.ZERO) {
            redisTemplate.opsForSet().add(RedisConstant.DB_FILE_UPLOAD_IMAGES, photoAlbumDTO.getCover());
            return R.success();
        }
        return R.error("添加照片失败");
    }

    /**
     * 修改相册
     * @param photoAlbumDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updatePhotoAlbum(PhotoAlbumDTO photoAlbumDTO) {
        PhotoAlbum photoAlbum = BeanCopyUtil.copyObject(photoAlbumDTO, PhotoAlbum.class);

        // 查询图片是否改变
        PhotoAlbum plainPhotoAlbum = baseMapper.selectById(photoAlbum.getId());

        int update = baseMapper.updateById(photoAlbum);

        if (update > Constant.ZERO && plainPhotoAlbum.getCover().equals(photoAlbum.getCover())) {
            redisTemplate.opsForSet().remove(RedisConstant.DB_FILE_UPLOAD_IMAGES, plainPhotoAlbum.getCover());
            redisTemplate.opsForSet().add(RedisConstant.DB_FILE_UPLOAD_IMAGES, photoAlbum.getCover());
        }

        return update > Constant.ZERO ? R.success() : R.error("修改照片失败");
    }

    /**
     * 删除相册
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteAlbumById(Integer id) {
        // 查出图片并在redis中删除
        List<String> photosImage = new ArrayList<>();
        PhotoAlbum photoAlbum = baseMapper.selectById(id);
        List<Photo> photos = photoMapper.selectList(new QueryWrapper<Photo>().eq(SqlConstant.ALBUM_ID, id));
        photos.forEach(photo -> photosImage.add(photo.getUrl()));
        redisTemplate.opsForSet().remove(RedisConstant.DB_FILE_UPLOAD_IMAGES, photoAlbum.getCover());
        redisTemplate.opsForSet().remove(RedisConstant.DB_FILE_UPLOAD_IMAGES, photosImage.toArray());


        baseMapper.deleteById(id);
        int delete = photoMapper.delete(new QueryWrapper<Photo>().eq(SqlConstant.ALBUM_ID, id));
        return delete > Constant.ZERO ? R.success(): R.error("删除相册失败");
    }









    // WEB方法
    /**
     * 查询相册所有图片
     * @return
     */
    @Override
    public R webAlbumList() {
        // 查出公开的所有相册
        List<PhotoAlbum> photoAlbums = photoAlbumMapper.selectList(new LambdaQueryWrapper<PhotoAlbum>()
                .select(PhotoAlbum::getId,PhotoAlbum::getCover,PhotoAlbum::getInfo,PhotoAlbum::getName,PhotoAlbum::getCreateTime,PhotoAlbum::getUpdateTime)
                .eq(PhotoAlbum::getStatus, YesOrNoEnum.NO.getCode()));

        List<PhotoAlbumsVO> photoAlbumsVOS = BeanCopyUtil.listCopy(photoAlbums, PhotoAlbumsVO.class);

        return R.success(photoAlbumsVOS);
    }

    /**
     * 查询相册的图片
     * @param albumId
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public R webListPhotos(Integer albumId, Integer pageNo, Integer pageSize) {

        HashMap<String, Object> hashMap = new HashMap();

        List<String> list = new ArrayList<>();
        // 查询相册的图片
        Page<Photo> photoPage = photoMapper.selectPage(new Page<Photo>(pageNo, pageSize), new LambdaQueryWrapper<Photo>().eq(Photo::getAlbumId, albumId).orderByDesc(Photo::getCreateTime));
        photoPage.getRecords().forEach(item -> list.add(item.getUrl()));

        // 查询相册名和相册首图
        PhotoAlbum photoAlbum = photoAlbumMapper.selectById(albumId);

        hashMap.put("photoAlbumCover", photoAlbum.getCover());
        hashMap.put("photoAlbumName", photoAlbum.getName());
        hashMap.put("photoList", list);

        return R.success(hashMap);
    }


    // 自定义方法


}


